package com.hang.util.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hang.mapper.ClazzStudentMapper;
import com.hang.model.ClazzStudent;
import com.hang.vo.ClazzStudentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ClazzStudentListener extends AnalysisEventListener<ClazzStudentVo> {
    private RedisTemplate redisTemplate;

    private ClazzStudentMapper clazzStudentMapper;
    private String clazzId;
    private List<String> students;

    public ClazzStudentListener(ClazzStudentMapper clazzStudentMapper,String clazzId,RedisTemplate redisTemplate) {
        this.clazzStudentMapper = clazzStudentMapper;
        this.clazzId = clazzId;
        this.redisTemplate = redisTemplate;
        students = new ArrayList<>();
    }

    @Override
    public void invoke(ClazzStudentVo clazzStudentVo, AnalysisContext analysisContext) {
        if(!ObjectUtils.isEmpty(clazzStudentVo.getStudentId())){
            //调用方法添加库
            ClazzStudent clazzStudent = new ClazzStudent();
            clazzStudent.setClazzId(clazzId);

            BeanUtils.copyProperties(clazzStudentVo,clazzStudent);
            clazzStudentMapper.insert(clazzStudent);
            students.add(clazzStudentVo.getStudentId());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        redisTemplate.opsForList().rightPush(clazzId,students);
        log.info("班级-学生数据在{}加载完成", LocalDateTime.now());
    }
}
